package dns

import (
	"fmt"

	alidns20150109 "github.com/alibabacloud-go/alidns-20150109/v4/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/istower/ssl_cert_auto/utils"
)

var (
	dnsClient *alidns20150109.Client
	_err      error
)

type Entry struct {
	Lang         string `json:"lang"`
	UserClientIp string `json:"user_client_ip"`
	DomainName   string `json:"domain_name"`
	RR           string `json:"rr"`
	EntryType    string `json:"entry_type"`
	Value        string `json:"value"`
	TTL          int64  `json:"ttl"`
	Line         string `json:"line"`
}

func NewDnsEntry(lang string, userClientIp string, domainName string, RR string, entryType string, value string, ttl int64, line string) *Entry {
	return &Entry{Lang: lang, UserClientIp: userClientIp, DomainName: domainName, RR: RR, EntryType: entryType, Value: value, TTL: ttl, Line: line}
}

func Init(ak *utils.AccessKey) {
	dnsClient, _err = utils.GeneratedDnsClient(tea.String(ak.AccessKeyID), tea.String(ak.AccessKeySecret))
	if _err != nil {
		utils.Log.Fatalf("连接阿里云失败,错误信息: %s", _err)
	}
}

func (de *Entry) CreateDnsEntry() (*alidns20150109.AddDomainRecordResponse, error) {
	addDomainRecordRequest := &alidns20150109.AddDomainRecordRequest{
		Lang:         tea.String(de.Lang),
		UserClientIp: tea.String(de.UserClientIp),
		DomainName:   tea.String(de.DomainName),
		RR:           tea.String(de.RR),
		Type:         tea.String(de.EntryType),
		Value:        tea.String(de.Value),
		TTL:          tea.Int64(de.TTL),
		Line:         tea.String(de.Line),
	}
	runtime := &util.RuntimeOptions{}
	res, tryErr := func() (res *alidns20150109.AddDomainRecordResponse, _e error) {
		defer func() {
			if r := tea.Recover(recover()); r != nil {
				_e = r
			}
		}()
		// 复制代码运行请自行打印 API 的返回值
		res, _err = dnsClient.AddDomainRecordWithOptions(addDomainRecordRequest, runtime)
		if _err != nil {
			fmt.Println(_err)
			return res, _err
		}
		return res, nil
	}()

	if tryErr != nil {
		var e = &tea.SDKError{}
		if _t, ok := tryErr.(*tea.SDKError); ok {
			e = _t
		} else {
			e.Message = tea.String(tryErr.Error())
		}
		// 如有需要，请打印 error
		_, _err = util.AssertAsString(e.Message)
		if _err != nil {
			return nil, _err
		}
	}
	return res, _err
}
